﻿namespace IBTrader.Modules.HistoricalData
{
    using IBTrader.Model;
    using IBTrader.Modules.Tws;
    using IBTrader.Properties;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Contract
    {
        internal string Symbol { get { return contract.Symbol; } }
        internal DateTime DateTime;
        internal event Action End;
        private readonly HistoricalData main;
        private readonly IIB ib;
        private readonly HistoricalContract contract;
        private static readonly List<DayOfWeek> WeekEnd = new List<DayOfWeek>(new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday });
        private static readonly IEnumerable<DateTime> Holidays = Settings.Default.Holidays.OfType<string>().Select(s => DateTime.Parse(s));
        internal Contract(HistoricalData main, IIB ib, HistoricalContract contract)
        {
            this.main = main;
            this.ib = ib;
            this.contract = contract;
            this.DateTime = contract.From;
        }
        internal void Next()
        {
            DateTime = DateTime.Add(contract.BarDuration);
            var total = contract.To - contract.From;
            var diff = contract.To - DateTime;
            var percent = 100 - ((diff.Ticks * 100) / total.Ticks);
            contract.Percent = Math.Max(percent, contract.Percent);
        }
        internal bool NextDate()
        {
            while (WeekEnd.Contains(DateTime.DayOfWeek) || Holidays.Contains(DateTime.Date))
                DateTime = DateTime.AddDays(1);
            bool next = DateTime <= contract.To && !main.Error.Failed;
            if ((!next) && End != null) 
                End();
            return next;
        }
        internal object CreateContract()
        {
            return ib.CreateContract(contract.Symbol, contract.SecurityType, contract.Exchange, contract.Currency, contract.Multiplier, contract.PrimaryExchange, DateTime);
        }
    }
}